const db = require('../db');

const express = require('express');
const router = express.Router();

//-------------------获取分类列表------------------------
router.get('/list', (req, res) => {
    let sql = 'select * from category';
    db(sql, (err, result) => {
        res.send({ status: 0, message: '获取分类成功', data: result });
    });
});
//--------------------添加分类----------------------
router.post('/add', (req, res) => {
    let { name, alias } = req.body;
    let sql = `insert into category set name='${name}',alias='${alias}'`;
    db(sql, (err, result) => {
        if (err) throw err;
        res.send({ status: 0, message: '添加分类成功' });
    });
});
//-------------删除分类-------------------
router.get('/delete/:id', (req, res) => {
    //获取req的query请求参数
    let id = req.query.id;
    db(`delete from category where id=${id}`, (err, result) => {
        if (err) throw err;
        //console.log(result);
        if (result.affectedRows > 0) {
            res.send({ status: 0, message: '删除分类成功' });
        } else {
            res.send({ status: 1, message: '删除分类失败' });
        };
    });
});
//---------------更新分类接口-----------------------
router.post('/update', (req, res) => {
    let { id, name, alias } = req.body;
    db(`update category set name='${name}',alias='${alias}' where id=${id}`, (err, result) => {
        if (err) throw err;
        console.log(result);
        if (result.affectedRows > 0) {
            res.send({ status: 0, message: '更新分类成功' });
        } else {
            res.send({ status: 1, message: '更新分类失败' });
        }
    })
});

//--------------根据id获取一个分类-------------------
router.get('/:id',(req,res)=>{
    console.log(req.params.id);
    db(`select * from category where id=${req.params.id}`,(err,result)=>{
        if(err)throw err;
        res.send({state:0,message:'获取分类成功',data:result[0]})
    })
})


module.exports = router;